import axios from 'axios'

// 创建axios实例
const request = axios.create({
    baseURL: '/api',
    timeout: 8000 // 请求超时时间
    // headers: {
    //     'Content-Type': 'application/json'
    // }
})

// request拦截器
request.interceptors.request.use(
    (config) => {
        const userInfo = JSON.parse(localStorage.getItem('userInfo') || '{}')
        config.headers['token'] = userInfo?.token || ''
        if (config.url.includes('merchant/import') || config.url.includes('file/upload')) {
            config.headers['Content-Type'] = 'multipart/form-data'
        }
        return config
    },
    (error) => {
        // 对请求错误做些什么
        return Promise.reject(error)
    }
)

// respone拦截器
request.interceptors.response.use(
    (response) => {
        if (response.data.success) {
            return response.data
        } else {
            if (response.data.code === 'NOT_LOGGED_IN') {
                window.location.href = '/login'
            }
            return Promise.resolve(response.data || 'Error')
        }
    },
    (error) => {
        // eslint-disable-next-line no-console
        console.log(error, '请求出错-error')
        const response = error.response || {}
        const { status } = response
        if (status === 401) {
            window.location.hash = '/login'
        }
        return Promise.reject(error)
    }
)

// axios重试机制
request.interceptors.response.use(undefined, function axiosRetryInterceptor(err) {
    const config = err.config
    // 如果config不存在或retry选项未设置，则拒绝
    if (!config || !config.retry) return Promise.reject(err)

    // 设置变量以跟踪重试计数
    config.__retryCount = config.__retryCount || 0

    // 检查是否已达到总重试次数上限
    if (config.__retryCount >= config.retry) {
        // 拒绝错误
        return Promise.reject(err)
    }

    // 增加重试计数
    config.__retryCount += 1

    // 创建新的promise以处理指数退避
    const backoff = new Promise(function (resolve) {
        setTimeout(function () {
            resolve()
        }, config.retryDelay || 1)
    })

    // 返回promise，其中重新调用axios以重试请求
    return backoff.then(function () {
        return axios(config)
    })
})

// 请求封装
const serve = (val) => {
    const { data, url, method, headers } = val
    if (method === 'get' || method === 'GET') {
        return request({ url, method, params: data, headers })
    } else {
        return request({ url, method, data, headers })
    }
}
export default serve
